package common.server.utils;

import java.io.InputStream;
import java.io.PipedOutputStream;
import java.net.HttpURLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ContentSender implements Runnable {

	private Log logger = LogFactory.getLog(getClass());
	private PipedOutputStream out = new PipedOutputStream();
	private HttpURLConnection connection;

	public PipedOutputStream getPipedOutputStream() {
		return out;
	}

	public void setConnection(HttpURLConnection connection) {
		this.connection = connection;
	}

	@Override
	public void run() {
		InputStream source = null;
		try {
			source = connection.getInputStream();
			byte[] b = new byte[10240];
			int length = 0;
			while ((length = source.read(b)) != -1) {
				out.write(b, 0, length);
			}
			out.flush();

		} catch (Exception e) {
			logger.warn("发送响应流异常  - " + e.getMessage(), e);
		} finally {
			if (source != null) {
				try {
					source.close();
				} catch (Exception e2) {
				}

				try {
					out.close();
				} catch (Exception e2) {
				}

				if (connection != null) {
					try {
						if (logger.isDebugEnabled()) {
							logger.debug("关闭连接[" + connection.getRequestMethod() + "] : " + connection.getURL() + " - ContentSender");
						}
						connection.disconnect();
					} catch (Exception e) {
					}
				}
			}
		}
	}
}
